$(document).ready(function() {
    $("#edit-unreg-student-wrapper").hide();
    var checked = 0;
    var camp = -1;
    var user = -1;
    var currentURL = window.location.pathname;
    $(".messages").after("<div id='select-orgs' class='select-orgs'><ul id='select-org' class='select-org'></ul></div>");
    $("#select-org li").live("click", function(event) {
        event.preventDefault();
        getReferralCode($(this).attr('value'), $(this).attr('id'), checked);
        $("#select-orgs").hide();
    });

    $(function() {
        var charity = false;
        var referral = false;
        $("#charity_opener").click(function() {
            charity = true;
            referral = false;
            $("#core101-referral-code-lookup-form .form-item").show();
            $("#edit-org-name-wrapper").hide();
            $("#edit-student-full-name-wrapper").hide();
            $("#edit-unreg-student-wrapper").hide();
        });
        $("#referral_opener").click(function() {
            referral = true;
            charity = false;
            $("#core101-referral-code-lookup-form .form-item").hide();
            $("#edit-org-name-wrapper").show();
            $("#edit-student-full-name-wrapper").show();
        });

        $("input:radio[name=charity_name]").click(function() {
            var camp_user = $(this).val();
            camp_user = camp_user.split('_');
            camp = camp_user[0];
            user = camp_user[1];
        });

        $("#referral_code_lookup_dialog").dialog({
            autoOpen: false,
            resizable: false,
            height: 500,
            modal: true,
            buttons: {
                "Enter": function() {
                    if (referral)
                        getReferralCode($("#edit-seller-id").val(), $("#edit-camp-id").val(), checked);
                    if (charity) {
                        getReferralCode(user, camp, 0);
                    }
                    $("#edit-org-name").val('');
                    $("#edit-student-full-name").val('');
                    $("#edit-camp-id").val('');
                    $("#edit-seller-id").val('');
                    allStudents = null;
                    $(this).dialog("close");
                    $("#select-orgs").hide();
                },
                Cancel: function() {
                    $(this).dialog("close");
                }
            }
        });
    });

    //Referral Code look up openner
    $("#referral_opener").click(function() {
        $("#referral_code_lookup_dialog").dialog("open");
    });
    //Charity look up openner
    $("#charity_opener").click(function() {
        $("#referral_code_lookup_dialog").dialog("open");
    });
    /*
     * Check if user joins more than one organization. 
     * If true, display list the organization(s) for user to select.
     */
    $(function() {
        var pageUrl = 'https://' + document.domain;
        var allOrganizations = new Array();
        var attach;
        if (document.domain === 'localhost') {
            pageUrl = 'http://' + document.domain;
            extraLink = '/fundraisingmagsdev';
        }
        else {
            extraLink = '';
        }
        var currentStep = currentURL.replace(extraLink, '');
        console.log(currentStep);
        if (currentStep === '/cart/checkout') {
            $.getJSON(pageUrl + extraLink + '/select_organization', function(json) {
                var user_id = json.pop();


                if (json.length > 1 && currentURL.indexOf("review") === -1) {
                    var selectOrgs = '';
                    $.each(json, function(index, array) {
                        selectOrgs += "<li id='" + array[1] + "' value=" + user_id + ">" + array[0] + "</li>";
                    });
                    $("#select-org").append(selectOrgs);
                }
                else {
                    var camp = json.pop();
                    getReferralCode(user_id, camp[1]);
                }

            });
        }
    });

    $(function() {
        var pageUrl = 'https://' + document.domain;
        var allOrganizations = new Array();
        var org = new Array();
        if (document.domain === 'localhost') {
            pageUrl = 'http://' + document.domain;
            extraLink = '/fundraisingmagsdev';
        }
        else {
            extraLink = '';
        }
        $.getJSON(pageUrl + extraLink + '/referral_code_org_lookup/', function(json) {
            $.each(json, function(index, array) {
                org = {
                    value: array['on_going_camp'],
                    label: array['title'] + '(' + array['field_org_city_value'] + ',' + array['field_org_state_value'] + ')',
                    sponsor_id: array['field_org_sponsor_uid'],
                    org_id: array['nid'],
                }
                allOrganizations.push(org);
            });
        });
        $("#edit-org-name").autocomplete({
            source: allOrganizations,
            minLength: 3,
            select: function(event, ui) {
                $("#edit-org-name").val(ui.item.label);
                $("#edit-camp-id").val(ui.item.value);
                getAllstudents(ui.item.sponsor_id, ui.item.org_id);

                return false;
            },
            response: function(event, ui) {

                // ui.content is the array that's about to be sent to the response callback.
                if (ui.content.length === 0) {

                    $("#edit-org-name-wrapper .ui-helper-hidden-accessible").html("No results found, please type in the correct school name that has an active campaign!");
                    $("#edit-org-name-wrapper .ui-helper-hidden-accessible").css({"color": "red"});
                } else {
                    $("#edit-org-name-wrapper .ui-helper-hidden-accessible").empty();
                }
            }

        });
    });
    $(function() {

        $("#edit-student-full-name").autocomplete({
            source: allStudents,
            minLength: 2,
            select: function(event, ui) {
                $("#edit-student-full-name").val(ui.item.label);
                $("#edit-seller-id").val(ui.item.value);
                return false;
            },
            response: function(event, ui) {
                // ui.content is the array that's about to be sent to the response callback.

                if (ui.content.length === 0) {
                    $("#edit-student-full-name-wrapper .ui-helper-hidden-accessible").html("No results found, please type in the correct student name or have the student register as a seller under his/her FundraisingMagazines school home page.</br> <label class='option' for='edit-no-student'><input id='edit-no-student' class='form-checkbox' type='checkbox' value='1' name='no_student'>Click here if you received program from mail.</label>");
                    $("#edit-student-full-name-wrapper .ui-helper-hidden-accessible").css({"color": "red"});
                    $('#edit-no-student').change(function() {
                        if (this.checked) {
                            $("#edit-unreg-student-wrapper").show();
                            $("#edit-student-full-name-wrapper").hide();
                            checked = 1;
                        } else {
                            $("#edit-unreg-student-wrapper").hide();
                            $("#edit-student-full-name-wrapper").show();
                            checked = 0;
                        }
                    });
                } else {
                    $("#edit-student-full-name-wrapper .ui-helper-hidden-accessible").empty();
                }
            }
        });
    });
    //fix the length of the fields to accommdate ARev fixed length fields

    $("#edit-panes-delivery-delivery-city").attr("maxlength", 20);
    $("#edit-panes-billing-billing-city").attr("maxlength", 20);
    $("#edit-panes-delivery-delivery-first-name").attr("maxlength", 15);
    $("#edit-panes-delivery-delivery-last-name").attr("maxlength", 15);
    $("#edit-panes-billing-billing-first-name").attr("maxlength", 15);
    $("#edit-panes-billing-billing-last-name").attr("maxlength", 15);
    $("#edit-panes-delivery-delivery-street1").attr("maxlength", 24);
    $("#edit-panes-delivery-delivery-street2").attr("maxlength", 24);
    $("#edit-panes-billing-billing-street1").attr("maxlength", 24);
    $("#edit-panes-billing-billing-street2").attr("maxlength", 24);
    $("#edit-panes-delivery-delivery-phone").attr("maxlength", 10);
    $("#edit-panes-delivery-delivery-phone-wrapper").append('<div class="description">ex:7162215082</div>');
    $("#edit-panes-billing-billing-phone").attr("maxlength", 10);
    $("#edit-panes-billing-billing-phone-wrapper").append('<div class="description">ex:7162215082</div>');
    $("#edit-panes-delivery-delivery-postal-code").attr("maxlength", 5);
    $("#edit-panes-delivery-delivery-postal-code-wrapper").append('<div class="description">ex:14213</div>');
    $("#edit-panes-billing-billing-postal-code").attr("maxlength", 5);
    $("#edit-panes-billing-billing-postal-code-wrapper").append('<div class="description">ex:14213</div>');

    //Go through checkout without registered seller.
    //Checkbox



});
var allStudents = new Array();

function getAllstudents(sponsorID, orgID) {
    var student = new Array();
    var pageUrl = 'https://' + document.domain;
    if (document.domain === 'localhost') {
        pageUrl = 'http://' + document.domain;
        extraLink = '/fundraisingmagsdev';
    }
    else {
        extraLink = '';
    }
    $.getJSON(pageUrl + extraLink + '/referral_code_stu_lookup/' + sponsorID, function(json) {
        $.each(json, function(index, array) {
            if (array['org_id'] === orgID) {
                student = {
                    value: array['student_id'],
                    label: array['firstname'] + ' ' + array['lastname'] + '(G:' + array['grade'] + ')',
                }

                allStudents.push(student);
            }
        });
    });
}
//@check if it's with registered or without register user
function getReferralCode(userid, campid, checked) {
    var referralcode;
    var pageUrl = 'https://' + document.domain;
    var infoString;
    if (document.domain === 'localhost') {
        pageUrl = 'http://' + document.domain;
        extraLink = '/fundraisingmagsdev';
    }
    else {
        extraLink = '';
    }
    campid = parseInt(campid);
    userid = parseInt(userid);
    if (!isNaN(userid) && !isNaN(campid) && checked == 0) {
        $.getJSON(pageUrl + extraLink + '/referral_code_lookup/' + userid + '/' + campid, function(json) {
            infoString = json.split(',');
            $('#edit-panes-extra-information-information-ucxf-referral-code').val(infoString[0]);
            $('#edit-panes-extra-information-information-ucxf-username').val(infoString[2]);
            $('#edit-panes-extra-information-information-ucxf-org-name').val(infoString[1]);
        });
        $(".messages").hide();
    } else if (!isNaN(campid) && checked == 1) {
        student_name = $('#edit-unreg-student').val();
        $.getJSON(pageUrl + extraLink + '/referral_code_no_seller/' + campid + '/' + student_name, function(json) {
            infoString = json.split(',');
            $('#edit-panes-extra-information-information-ucxf-referral-code').val(infoString[0]);
            $('#edit-panes-extra-information-information-ucxf-username').val(infoString[2]);
            $('#edit-panes-extra-information-information-ucxf-org-name').val(infoString[1]);
        });
        $(".messages").hide();
    }

}